package com.usian.gateway.filter;

import com.usian.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * token校验
 */

@Component//被扫描
@Log4j2//获取日志
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //获取用户的请求路径以及携带的参数
        ServerHttpRequest request=exchange.getRequest();
        //获取我们作相应到浏览器上 返回401认证失败
        ServerHttpResponse response=exchange.getResponse();

        //使用放行路径
        //判断当前的请求是否为登录，如果是，就放行
        if (request.getURI().getPath().contains("/login/in")){
            //放行
            return chain.filter(exchange);
        }
        //获取token
        String jwtToken = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(jwtToken)){
            //如果不存在，向客户端返回错误信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //jwtToken是有值的 但是不确定是否合法
        //直接解析token 确定token是合法的
      try{
          Claims claims=AppJwtUtil.getClaimsBody(jwtToken);
          int result = AppJwtUtil.verifyToken(claims);
//          System.out.println(result);
          //直接携带token放行
          if(result == 0 || result == -1){
              //5.1 合法，则向header中重新设置userId
              Integer id = (Integer) claims.get("id");
              log.info("find userid:{} from uri:{}",id,request.getURI());
              //重新设置token到header中
              ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                  httpHeaders.add("userId", id + "");
              }).build();
              exchange.mutate().request(serverHttpRequest).build();
          }else {
              response.setStatusCode(HttpStatus.UNAUTHORIZED);
              return response.setComplete();
          }
      }catch (Exception e){
          //如果不存在，向客户端返回错误信息
          response.setStatusCode(HttpStatus.UNAUTHORIZED);
          return response.setComplete();
      }
        //6.放行
        return chain.filter(exchange);
    }
//优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
